#include "cmdthread.h"
#include <QStringList>

int CMDThread::qflag = 0;
CMDThread::CMDThread(QString mode,QObject *parent) :
    QThread(parent)
{
    LuanchMode = mode;
}

void CMDThread::run()
{
    QStringList options;
    emit signal_cmd_out(tr("Preparing update..."));
    QProcess proc;

/*
    //验证服务序列号
    QString license1,license2;
    char buff1[5000] = {0};
    char buff2[5000] = {0};
    FILE * licensefile1 = popen("cat /usr/share/kylin-update-desktop/.kyinfo |grep key","r");
    while((fgets(buff1, sizeof(buff1), licensefile1)) != NULL)
    {
        license1 = QString(buff1);

        emit signal_cmd_out(license1);
    }

    FILE * licensefile2 = popen("cat /etc/.kyinfo |grep key","r");
    while((fgets(buff2, sizeof(buff2), licensefile2)) != NULL)
    {
        license2 = QString(buff2);

        emit signal_cmd_out(license2);
    }


    if (license1!=license2)
    {
        emit signal_cmd_out(tr("\n Service serial number is inconsistent!\n"));
        emit signal_is_complete(0);
//        emit signal_pb_startupdate_enabled();
        CMDThread::qflag = 0;
        return ;
    }
*/
    
//临时关闭锁屏
//    system("mate-screensaver-command --exit");
//    QFile::copy("./ksudata", "/tmp/kylin-simpleupdate.tar");

    emit signal_cmd_out(tr("\n Start the upgrade...\n"));
/*
    char buff[5000] = {0};
    FILE * out = popen("tar -xvf /tmp/kylin-simpleupdate.tar -C /tmp", "r");
    QString line;
    while((fgets(buff, sizeof(buff), out)) != NULL)
    {
        line = QString(buff);

        emit signal_cmd_out(line);
    }

    proc.start("tar -xvf /tmp/kylin-simpleupdate.tar -C /tmp");
    if (!proc.waitForStarted())  // 等待进程启动
     {
        emit signal_cmd_out("\n升级包解压失败，请重试升级......\n");
//        emit signal_pb_startupdate_enabled();
        CMDThread::qflag = 0;
        return ;
    }
    else
    {
        while(proc.waitForReadyRead(3000000) == true)
        {
            procoutput = proc.readLine();
            emit signal_cmd_out(procxoutput.data());
        }
        proc.waitForFinished();  // 等待进程结束
    }
*/
    bool ret = get_battery();
    qDebug() << ret;
    /*升级前判断电量是否充足*/
    if (!ret){
        emit signal_lower_battery();
        return ;
    }

    //因为在执行核心脚本时会将软件包删除所以需要提前将信息获取
    this->get_version_and_description();
//执行升级核心脚本
    options << "-c";
    options << "pkexec   /usr/share/kylin-update-desktop/installation_special.sh | tee -a ~/.cache/kylin-update-desktop.log";
    system("date | tee -a ~/.cache/kylin-update-desktop.log");
    qDebug()<<options;
    proc.start("/bin/bash", options);
    if(LuanchMode == "SILENCE")
    {
        emit signal_hide_mainwindow();
    }
    if (!proc.waitForStarted())
    {
        this->get_pingback_value();
        //this->pingback("Fail");
        //this->insert_imformation_to_db("Fail");
        emit signal_cmd_out(tr("\n The program failed. Please try again later...\n"));
        emit signal_is_complete(2);
//        emit signal_pb_startupdate_enabled();
        CMDThread::qflag = 0;
        return ;
    }
    else if(proc.waitForReadyRead(3000000) == true)
    {
        this->get_pingback_value();
        //this->pingback("Seccuss");
        //this->insert_imformation_to_db("Seccuss");
        procoutput = proc.readLine();
        emit signal_cmd_out(procoutput.data());
        while(proc.waitForReadyRead(3000000) == true)
        {
            procoutput = proc.readLine();
            emit signal_cmd_out(procoutput.data());
        }
        proc.waitForFinished();
/*        emit signal_cmd_out("\n正在重置桌面......");

        proc.start("mate-panel --reset");
        if (!proc.waitForStarted())
        {
            emit signal_cmd_out("\n 桌面重置失败，重试中......\n");
            proc.start("mate-panel --reset");
            if (!proc.waitForStarted())
            {
                emit signal_cmd_out("\n 桌面重置异常，请重试升级......\n");
//                emit signal_pb_startupdate_enabled();
                CMDThread::qflag = 0;
                return ;
             }
        }
        else
        {
            while(proc.waitForReadyRead(3000000) == true)
            {
                procoutput = proc.readLine();
                emit signal_cmd_out(procoutput.data());
            }
            proc.waitForFinished();  // 等待进程结束
        }
*/
        system("rm ~/.cache/mate/background/*");

        emit signal_cmd_out(tr("\n Restart the computer...\n"));
        emit signal_messagebox();
        system("echo Upgrade is complete, restart the computer... | tee -a ~/.cache/kylin-update-desktop.log");

    }
    else
    {
        //提权失败
        this->get_pingback_value();
        //this->pingback("Fail");
        //qDebug()<<"error";
        //this->insert_imformation_to_db("Fail");
        emit signal_cmd_out(tr("\n Fail to authenticate. Please try again later...\n"));
        emit signal_is_complete(1);
        system("echo Fail to authenticate. Please try again later... | tee -a ~/.cache/kylin-update-desktop.log");
//        emit signal_pb_startupdate_enabled();
    }
    CMDThread::qflag = 0;
}

//获取软件包版本以及描述
void CMDThread::get_version_and_description()
{
    QString path = "/usr/share/kylin-update-desktop";
    QString changelog_path = path +"/changelog";
    string open_changelog_path = changelog_path.toStdString();
    qDebug()<<changelog_path;
    QString c = "";
    char ch;
    ifstream in;
    in.open(open_changelog_path,ios::in);
    while(1)
    {
        in.get(ch);
        c = ch;
        /*if( feof(in) )
        {
            break ;
        }*/
        if(c == ")")
        {
            break;
        }
        else
        {
            app_version = app_version + c;
        }
    }
    //fclose(fp);
    in.close();
    char str[512] = {0};
    int position;
    qstrcpy(str,app_version.toStdString().c_str());
    app_version = "";
    qDebug() <<strlen(str);
    for(int i=0;i<strlen(str);i++)
    {
        if(str[i] == '(')
        {
            position =i;
            qDebug()<<i;
        }
    }
    for(int i=0;i<strlen(str);i++)
    {
        if(i>position)
        {
            app_version = app_version +str[i];
        }
    }
    qDebug() << app_version;
    QString update_path = path + "/update_log";
    string open_log_path = update_path.toStdString();
    qDebug() << update_path;
    ifstream change_log;
    change_log.open(open_log_path,ios::in);
    char ch2[512] = {0};
    while(change_log.getline(ch2,512))
    {
        app_description = app_description +ch2;
    }
    change_log.close();
    qDebug()<<app_description;
}

//将软件包信息插入数据库
void CMDThread::insert_imformation_to_db(QString statue)
{
    qDebug()<<"start insert to db";
    Installed_imformation *installed_imformation = new Installed_imformation();

    installed_imformation->insert("kylin-update-desktop",app_version,app_description,"/usr/share/pixmaps/",statue);
}

void CMDThread::get_pingback_value()
{
    //获取本地ip地址
    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i)
    {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&ipAddressesList.at(i).toIPv4Address())
        {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    ip = ipAddress;
    qDebug()<<"ip = "<<ip;
    //获取系统版本
    ifstream fp;
    fp.open("/etc/lsb-release",ios::in);
    char ch[512] = {0};
    int i;
    int j;
    QString get_conf = "";
    while(fp.getline(ch,512))
    {
      for(i=0;i<strlen(ch);i++)
      {
          if(ch[i] == '=')
          {
              break;
          }
          get_conf = get_conf + ch[i];
      }
      if(get_conf == "DISTRIB_KYLIN_RELEASE")
      {
          for(j=i+1;j<strlen(ch);j++)
          {
              version = version+ch[j];
          }
      }
      get_conf = "";
    }
    qDebug()<<"version = "<<version;
    fp.close();
    //获取软件版本
    soft_version = get_appversion("dpkg -l|grep kylin-update-manager");
    qDebug() <<"soft_version = "<<soft_version;
    //获取SP升级包版本
    SPpkg_version = get_appversion("dpkg -l|grep kylin-update-desktop");
    qDebug() <<"SPpkg_version = "<<SPpkg_version;
    //获取当前时间
    time_t time1 = time(NULL);
    tm *time2;
    time2 = localtime(&time1);
    time2->tm_year = time2->tm_year;
    char tmp[512] = {};
    strftime(tmp,sizeof(tmp),"%Y-%m-%d %H:%M:%S",time2);
    datetime = tmp;
    char tmp2[512] = {};
    strftime(tmp2,sizeof(tmp2),"%Y%m%d%H%M",time2);
    time3 = tmp2;
    qDebug()<<"time3 = "<<time3;
    //获取mac地址
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    for(int i = 0; i < nCnt; i ++)
    {
      // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
      if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
      {
          host_mac = nets[i].hardwareAddress();
          break;
      }
    }
    qDebug()<<"mac = "<<host_mac;

}

void CMDThread::pingback(QString status)
{
    //访问url
    QNetworkAccessManager *accessManager_send_information = new QNetworkAccessManager();
    QString Url = "http://archive.kylinos-intranet.cn/kylin-update-manager-server/main.php?";
    Url = Url +QString::fromUtf8("ip=") + ip
          + QString::fromUtf8("&version=") + version
          + QString::fromUtf8("&soft_version=") + soft_version
          + QString::fromUtf8("&host_mac=") + host_mac
          + QString::fromUtf8("&datetime=") + datetime
          + QString::fromUtf8("&appname=") + "kylin-update-desktop"
          + QString::fromUtf8("&appversion=") + SPpkg_version
          + QString::fromUtf8("&status=") + status
          + QString::fromUtf8("&filename=")+host_mac+ip+time3+".log";
    emit get_file_name(QString::fromUtf8("&filename=")+host_mac+ip+time3+".log");
    qDebug()<<Url;
    QUrl serviceUrl(Url);
    //qDebug()<<data;
    QNetworkRequest request_registered;
    request_registered.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    //request_registered.setHeader(QNetworkRequest::ContentLengthHeader,data.length());
    //qDebug() <<data.length();
    request_registered.setUrl(serviceUrl);
    FILE * check_machine = popen("uname -m","r");
    char buff[512] = {0};
    QString machine = "";
    while((fgets(buff, sizeof(buff), check_machine)) != NULL)
    {
        machine = QString(buff);
    }
    machine = machine.replace("\n","");
    qDebug()<<machine;
    if(machine !="mips64")
    {
        QNetworkReply* registered = accessManager_send_information->get(request_registered);
    }
    qDebug()<<"pingback_over";

}
/*
 * 获取电量值，是否满足SP升级条件
*/
bool CMDThread::get_battery()
{
    qDebug() <<"获取电量";
    QStringList users;
    int battery_value = 0;
    QDBusInterface m_interface1( "org.freedesktop.UPower",
                                "/org/freedesktop/UPower",
                                "org.freedesktop.UPower",
                                QDBusConnection::systemBus() );
    if (!m_interface1.isValid()) {
        qDebug() << "电源管理器dbus接口初始化失败";
        return true;
    }

    QDBusReply<QList<QDBusObjectPath>> obj_reply = m_interface1.call("EnumerateDevices");

    if (obj_reply.isValid()) {
        for (QDBusObjectPath op : obj_reply.value())
             users << op.path();
        if (users.size()==1 || users.isEmpty()) {
            qDebug()<<"无法获取电量值,判断此电脑为台式电脑";
            return true;
        }
        foreach (QString str, users) {
            qDebug() <<"获取电量22222" << str;
//            if (str == users.at(0) || str == users.at(users.size() - 1)) {
//                continue ;
//            }
            QDBusInterface m_interface( "org.freedesktop.UPower",
                                        str,
                                        "org.freedesktop.DBus.Properties",
                                        QDBusConnection::systemBus());

            if (!m_interface.isValid()) {
                qDebug() << "电源管理器dbus接口初始化失败";
                return true;
            }

            QDBusReply<QVariant> obj_reply = m_interface.call("Get","org.freedesktop.UPower.Device","Percentage");
            qDebug() << "---------------->" << obj_reply.value().toDouble();
            int Ele_surplus = obj_reply.value().toInt();
            battery_value += Ele_surplus;
            qDebug() << "battery value : " << Ele_surplus << "------------------------------";
        }
     } else {
        qDebug() << "battery value is -------->";
    }
    /*如果电池总电量小于30不可升级*/
    if (battery_value < 60)
        return false;
    return true;
}

QString CMDThread::get_appversion(char *cmd)
{
    int i;
    char get_version[512] = {0};
    FILE *fp1 = popen(cmd,"r");
    fread(get_version,sizeof(char),sizeof(get_version),fp1);
    QString pkg_version ="";
    pkg_version = get_version;
    QStringList get_softversion = pkg_version.split(QRegExp("[ ]"));
    int count = 0;
    pkg_version = "";
    for(i=0;i<get_softversion.length();i++)
    {
      if(get_softversion[i]!="")
      {
          count = count + 1;
      }
      if(count == 3)
      {
          pkg_version = get_softversion[i];
          break;
      }
    }

    qDebug() <<"soft_version = "<<pkg_version;
    return pkg_version;
}
